package com.slj.comm.advice;

import com.slj.comm.api.ResultCode;
import com.slj.comm.exception.ResourceNotFoundException;
import com.slj.comm.responce.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author CC
 * @version 1.0
 * @description: 全局异常处理类
 * @date 2025/9/17 16:33
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 请求方式异常处理
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public R<String> handle(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        log.error("请求方式异常: 请求路径={}, 错误信息={}", request.getRequestURI(), e.getMessage(), e);
        return R.fail(ResultCode.METHOD_NOT_ALLOWED);
    }
    //分母不能为0异常
    @ExceptionHandler(value = ArithmeticException.class)
    public R<String> handle(HttpServletRequest request, ArithmeticException e) {
        log.error("分母不能为0异常: 请求路径={}, 错误信息={}", request.getRequestURI(), e.getMessage(), e);
        return R.fail(500, "分母不能为0异常");
    }
    @ExceptionHandler(value = ResourceNotFoundException.class)
    public R<String> handle(HttpServletRequest request, ResourceNotFoundException e) {
        log.error("资源未找到异常: 请求路径={}, 错误信息={}", request.getRequestURI(), e.getMessage(), e);
        return R.fail(ResultCode.NOT_FOUND);
    }


    // 全局异常处理
    /*@ExceptionHandler(value = Exception.class)
    public R<String> handle(HttpServletRequest request, Exception e) {
        log.error("全局异常: 请求路径={}, 错误信息={}", request.getRequestURI(), e.getMessage(), e);
        return R.fail(500, "服务器内部错误，请联系管理员");
    }*/
}
